/**
 * @Title: DatbRecordSyncLogic.java
 * @Package: com.jason.fingerprint.logic
 * @Descripton: TODO
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2014年10月21日 上午9:54:27
 * @Version: V1.0
 */
package com.jason.fingerprint.logic;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.google.gson.GsonBuilder;
import com.jason.fingerprint.AppContext;
import com.jason.fingerprint.AppGlobal;
import com.jason.fingerprint.beans.RecordBean;
import com.jason.fingerprint.beans.RecordResp;
import com.jason.fingerprint.beans.ui.FingerPrintBean;
import com.jason.fingerprint.common.UIHelper;
import com.jason.fingerprint.configs.HttpConfig;
import com.jason.fingerprint.utils.CodecUtils;

import org.kymjs.aframe.utils.StringUtils;

import java.util.List;

import cn.finalteam.okhttpfinal.BaseHttpRequestCallback;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.RequestParams;
import okhttp3.Headers;

/**
 * @ClassName: DatbRecordSyncLogic
 * @Description: 同步矫正人员的信息
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2014年10月21日 上午9:54:27
 */
public class DatbRecordSyncLogic extends Logic {

	private static final String TAG = "DatbRecordSyncLogic";

	private Handler mHandler;
	private boolean mIsCallBack;// 是否有回调，此需要Handle
	private int mCurrentIndex = 1;// 当前页
	private int mCount;
	private Message mMessage;


	public DatbRecordSyncLogic(AppContext appContext, Handler handler) {
		super(appContext);
		this.mHandler = handler;
		this.mMessage = new Message();
	}

	public DatbRecordSyncLogic(AppContext appContext, Handler handler,
			boolean isCallBack) {
		super(appContext);
		this.mHandler = handler;
		this.mMessage = new Message();
		this.mIsCallBack = isCallBack;
	}

	@Override
	public void execute() {
		Log.i(TAG, "-----run time ---001-->" + System.currentTimeMillis());
//		initAsyncFingerprint();
		try {
			//mKjdb.deleteTable("table_record");
			//mKjdb.deleteByWhere(RecordBean.class, null);
			mKjdb.deleteTable(RecordBean.class);
			//删除矫正人员的指纹信息
			mKjdb.deleteByWhere(FingerPrintBean.class, "type = 1");
		} catch (Exception e) {
		}
		Log.i(TAG, "-----run time ---002-->" + System.currentTimeMillis());
		datbRecordSync();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.jason.fingerprint.logic.Logic#send()
	 */
	@Override
	public void send() {
		if (mIsCallBack) {
			mHandler.sendMessage(mMessage);
			mMessage = new Message();
		}

	}

	// 档案同步
	private void datbRecordSync() {
		Log.i(TAG, "-----run time ---005-->" + System.currentTimeMillis());
		mParams = new RequestParams();
		mParams.addFormDataPart(AppGlobal.HTTP_PARAM_IMEI, mImei);
		mParams.addFormDataPart(AppGlobal.HTTP_PARAM_CURRENTINDEX,
				String.valueOf(mCurrentIndex));
		mParams.addFormDataPart(AppGlobal.HTTP_PARAM_ORGANID, mMachId);
		String url = HttpConfig.POST_URL_DATB_RECORDSYNC;
		Log.i(TAG, "----->API:" + url);
		Log.i(TAG, "----->mCurrentIndex:" + mCurrentIndex);
		Log.i(TAG, "-----run time ---006-->" + System.currentTimeMillis());
		HttpRequest.post(url, mParams, new BaseHttpRequestCallback<String>() {

			@Override
			protected void onSuccess(String o) {
				super.onSuccess(o);
				if (o == null){
					mMessage.arg1 = 1;
					send();
					return;
				}
				String result = CodecUtils.base64Decode(o);
				Log.i(TAG, "----->Result:" + result);
				RecordResp recordResp = new GsonBuilder().create().fromJson(
						result, RecordResp.class);
				// 存入数据库
				if (recordResp != null && !recordResp.isEmpty()) {
					Log.i(TAG, "----->organResp:" + recordResp.toString());
					List<RecordBean> beans = recordResp.getValues();
					try {
						for (RecordBean recordBean : beans) {
							if (recordBean != null) {
								String userId = recordBean.getElectronicsId();
								String userName = recordBean.getName();
								String fp1 = recordBean.getFp_1();
								String fp2 = recordBean.getFp_2();
								String cardNo = recordBean.getCardNO();
								if (StringUtils.isEmpty(fp1)
										&& StringUtils.isEmpty(fp2)) {
									recordBean.setIsEntry(0);
								} else {
									recordBean.setIsEntry(1);
								}
								Log.i(TAG, "--------->recordBean:" + recordBean);
								mKjdb.save(recordBean);
								// 保存工作人员指纹信息
								// 如果存在更新数据，如果不存在添加
								Log.i(TAG, "-----run time ---011-->" + System.currentTimeMillis());
								addOrUpdateFingerPrintInfo(new FingerPrintBean(userId,
										userName, fp1,cardNo, 1, 1));
								Log.i(TAG, "-----run time ---012-->" + System.currentTimeMillis());
								addOrUpdateFingerPrintInfo(new FingerPrintBean(userId,
										userName, fp2,cardNo, 1, 2));
								mCount++;
							}
						}
						if (!recordResp.isLastPage()) {
							mCurrentIndex++;
							datbRecordSync();
						} else {
//							saveFinger();
							Log.i(TAG, "-----run time ---013-->" + System.currentTimeMillis());
							// 通知
							mMessage.arg1 = 0;
							mMessage.arg2 = mCount;
							send();
						}
					} catch (Exception e) {
						mMessage.arg1 = 1;
						send();
					}
				} else {
					mMessage.arg1 = 2;
					send();
				}
			}

			@Override
			public void onResponse(String response, Headers headers) {
			}

			@Override
			public void onFailure(int errorCode, String msg) {
				super.onFailure(errorCode, msg);
				Log.i(TAG, "----->Result:arg1:" + errorCode + ",arg2:" + msg);
				if (errorCode == UIHelper.HTTP_CODE_TIMEOUT){
					mMessage.what = UIHelper.HTTP_CODE_TIMEOUT;
				}else {
					mMessage.what = 3;
				}
				send();
			}
		});
	}

	private void addOrUpdateFingerPrintInfo(FingerPrintBean bean) {
		if (bean != null) {
			try {
				List<FingerPrintBean> beans = mKjdb.findAllByWhere(FingerPrintBean.class,
						"userId = '" + bean.getUserId()
								+ "' and type = 1 and state = " + bean.getState());
				if (beans != null && !beans.isEmpty()) {
					FingerPrintBean b = beans.get(0);
					bean.setId(b.getId());
					mKjdb.update(bean);
				}else {
					mKjdb.save(bean);
				}
			} catch (Exception e) {
			}
		}
	}

	/* (non-Javadoc)
	 * @see com.jason.fingerprint.logic.Logic#destory()
	 */
	@Override
	public void destory() {
		// TODO Auto-generated method stub
		
	}

}
